<script setup lang="ts">
import { Search, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { getUserListApi, delUserApi, updateUserApi } from '@/api/user'
import type { UserInfo } from '@/types/data'
import { ElMessageBox, ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { checkMobile } from '@/utils/validate'

const expand = ref(false)
const userForm = ref({
  username: '',
  mobile: '',
  role_name: '',
  created_at: '',
  updated_at: '',
  pagenum: 1,
  pagesize: 10,
})
const total = ref(0)

//--------------获取用户列表--------------
const userList = ref([] as UserInfo[])
const getUserList = async () => {
  const res = await getUserListApi(userForm.value)
  userList.value = res.data.list!
  total.value = res.data.total!
}
getUserList()

// 每页显示条数发生改变时触发
const handleSizeChange = (newSize: number) => {
  //   console.log('ok', newSize)
  userForm.value.pagesize = newSize
  getUserList()
}
// 页码值改变时触发
const handleCurrentChange = (newPage: number) => {
  //   console.log(newPage)
  userForm.value.pagenum = newPage
  getUserList()
}

//----------------- 删除用户----------
const delUser = async (row: UserInfo) => {
  // 使用ElementPlus确认框
  const res = await ElMessageBox.confirm('确定要删除该用户吗?', '删除用户').catch((error) => error)
  if (res === 'cancel') return

  await delUserApi(row)
  ElMessage.success('删除成功')
  getUserList()
}

// ----------------编辑用户-----------
const editUserVisible = ref(false)
const editUserInfo = ref({
  user_id: 0,
  username: '',
  password: '',
  mobile: '',
})
const editUserFormRef = ref<FormInstance>()
const editUserInfoRules = {
  // 1.用户名必填
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  // 2.密码必填，长度在6~16位之间
  password: [{ min: 6, max: 16, message: '长度应在6~16位之间', trigger: 'blur' }],
  // 3.手机号校验
  mobile: [
    {
      validator: (rules: object, value: string, callback: (params?: object) => void) => {
        if (checkMobile(value)) {
          callback()
        } else {
          callback(new Error('手机号不合法'))
        }
      },
      trigger: 'blur',
    },
  ],
}
const editUser = (row: UserInfo) => {
  // 1.弹出框显示
  editUserVisible.value = true
  // 2.表单赋值
  editUserInfo.value.user_id = row.user_id
  editUserInfo.value.username = row.username
  editUserInfo.value.mobile = row.mobile
  // editUserInfo.value = row
}
const updateUser = async () => {
  // 1.手动校验
  // 2.更新
  const res = await updateUserApi(editUserInfo.value)
  if (res.data.state !== 200) {
    return ElMessage.error(res.data.msg)
  } else {
    editUserVisible.value = false
    ElMessage.success('更新用户成功')
    getUserList()
  }
}
const updateReset = () => {
  editUserFormRef.value?.resetFields()
}
</script>

<template>
  <!-- 搜索区域 -->
  <el-card style="margin-bottom: 15px">
    <el-form :inline="true">
      <el-form-item label="用户名">
        <el-input placeholder="请输入用户名"></el-input>
      </el-form-item>

      <el-form-item label="手机号">
        <el-input placeholder="请输入手机号"></el-input>
      </el-form-item>

      <el-form-item label="角色名" v-if="expand">
        <el-input placeholder="请输入角色名"></el-input>
      </el-form-item>

      <el-form-item label="创建于" v-if="expand">
        <el-date-picker
          type="daterange"
          range-separator="到"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="default"
        />
      </el-form-item>

      <el-form-item label="更新于" v-if="expand">
        <el-date-picker
          type="daterange"
          range-separator="到"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="default"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :icon="Search">搜索</el-button>
        <el-button>重置</el-button>
        <el-button type="primary" link @click="expand = !expand">
          {{ expand ? '收起' : '展开' }}
          <el-icon>
            <template v-if="expand"><ArrowUp /></template>
            <template v-else><ArrowDown /></template>
          </el-icon>
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!-- 表格区域 -->
  <el-card class="box-card">
    <template #header>
      <el-button type="primary">添加</el-button>
    </template>
    <!-- 表格 -->
    <el-table :data="userList" height="385" style="width: 100%" border stripe>
      <el-table-column prop="user_id" label="编号" width="150" align="center" />
      <el-table-column prop="role_name" label="所属角色" width="120" align="center" />
      <el-table-column prop="avatar" label="头像" width="120" align="center">
        <template v-slot="{ row }">
          <img :src="row.avatar" alt="" style="width: 40px; height: 40px" />
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="120" align="center" />
      <el-table-column prop="mobile" label="手机号" width="120" align="center" />
      <el-table-column prop="state" label="登录" width="120" align="center">
        <template v-slot="{ row }">
          <el-switch v-model="row.state" :active-value="1" :inactive-value="0" />
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建于" width="200" align="center" />
      <el-table-column prop="updated_at" label="更新于" width="200" align="center" />
      <el-table-column fixed="right" label="操作" width="250" align="center">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="editUser(row)">编辑</el-button>
          <el-button type="success" size="small">分配角色</el-button>
          <el-button type="danger" size="small" @click="delUser(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页
     current-page：当前页码值
     page-size：每页显示条数
     page-sizes：设置每页显示条数
     small:分页组件大小
     disabled:是否禁用
     background:背景颜色
     layout:组件布局
     total:总条数

     @size-change：每页显示条数发生改变时触发
     @current-change：页码值改变时触发
    -->
    <el-pagination
      v-model:current-page="userForm.pagenum"
      v-model:page-size="userForm.pagesize"
      :page-sizes="[2, 3, 5, 10]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>

  <!-- 编辑弹出框 -->
  <el-dialog v-model="editUserVisible" title="编辑用户" width="50%">
    <el-form
      :model="editUserInfo"
      :rules="editUserInfoRules"
      ref="editUserFormRef"
      label-width="auto"
      size="large"
    >
      <el-form-item label="用户名" prop="username">
        <el-input placeholder="请输入用户名" v-model="editUserInfo.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input placeholder="请输入密码" v-model="editUserInfo.password"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input placeholder="请输入手机号" v-model="editUserInfo.mobile"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateUser">更新</el-button>
        <el-button @click="updateReset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-pagination {
  margin: 15px 0;
}
</style>
